package io.renren.modules.sys.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.renren.common.exception.RRException;
import io.renren.common.util.JsonUtils;
import io.renren.config.GlobalConfig;
import io.renren.modules.common.BaseService;
import io.renren.modules.sys.dao.SysConfigDao;
import io.renren.modules.sys.entity.SysConfigEntity;
import io.renren.modules.sys.pojo.SysConfigQuery;
import io.renren.modules.sys.service.SysConfigService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("sysConfigService")
@CacheConfig(cacheNames = GlobalConfig.CACHE_KEY_PREFIX + "sys_config")
public class SysConfigServiceImpl extends BaseService
		implements SysConfigService {
	@Autowired
	private SysConfigDao sysConfigDao;
	
	@Override
	@Transactional
	@CachePut(key = "#config.key")
	public void save(SysConfigEntity config) {
		sysConfigDao.save(config);
	}

	@Override
	@Transactional
	@CachePut(key = "#config.key")
	public void update(SysConfigEntity config) {
		sysConfigDao.update(config);
	}

	@Override
	@Transactional
	@CacheEvict(key = "#key")
	public void updateValueByKey(String key, String value) {
		sysConfigDao.updateValueByKey(key, value);
	}

	@Override
	@Transactional
	@CacheEvict(allEntries = true)
	public void deleteBatch(Long[] ids) {
		sysConfigDao.deleteBatch(ids);
	}

	@Override
	public List<SysConfigEntity> queryList(SysConfigQuery query) {
		return sysConfigDao.queryList(query);
	}

	@Override
	public PageInfo<SysConfigEntity> queryPage(SysConfigQuery query) {
		return PageHelper.startPage(query.getPage(),query.getLimit())
				.doSelectPageInfo(() -> sysConfigDao.queryList(query));
	}

	@Override
	public long queryTotal(SysConfigQuery query) {
		return PageHelper.count(() -> sysConfigDao.queryList(query));
	}

	@Override
	public SysConfigEntity queryObject(Long id) {
		return sysConfigDao.queryObject(id);
	}

	@Override
	@Cacheable(key = "#key")
	public String getValue(String key) {
		SysConfigEntity config = sysConfigDao.queryByKey(key);
		return config.getValue();
	}
	
	@Override
	@Cacheable(key = "#key")
	public <T> T getConfigObject(String key, Class<T> clazz) {
		String value = getValue(key);
		if(StringUtils.isNotBlank(value)){
			return JsonUtils.fromJson(value, clazz);
		}

		try {
			return clazz.newInstance();
		} catch (Exception e) {
			throw new RRException("获取参数失败");
		}
	}
}
